#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include "znet.h"
#include "tunnel.h"

int main(int argc, char *argv[])
{
    char rxbuf[1024] = {0};
    char txbuf[1024] = {0};

    if (argc != 4) {
        printf("tx <addr> <port> <channel>\n");
        return -1;
    }

    char *addr = argv[1];
    int port = atoi(argv[2]);
    int channel = atoi(argv[3]);

    znet_t znet = {0};
    znet.port = port;
    znet.addr = addr;

    znet_launch(&znet, ZNET_CLIENT);

#ifdef TX
    int ret = tunnel_tx(znet.sock, channel);
#endif
#ifdef RX
    int ret = tunnel_rx(znet.sock, channel);
#endif
    if (ret < 0)
        printf("tunnel error: %d\n", ret);

    fd_set readfds;
    int maxfd = znet.sock;

    for (;;) {
        memset(txbuf, 0, sizeof(txbuf));
        memset(rxbuf, 0, sizeof(rxbuf));

        FD_ZERO(&readfds);
        FD_SET(znet.sock, &readfds);
        FD_SET(0, &readfds);
        int ready = select(maxfd + 1, &readfds, NULL, NULL, NULL);
        if (ready <= 0) {
            printf("select error!\n");
            return -1;
        } else {
            if (FD_ISSET(znet.sock, &readfds)) {
                if (znet_recv(znet.sock, rxbuf, sizeof(rxbuf)) <= 0) {
                    printf("Disconnected!\n");
                    return -1;
                }
                printf("\033[36m%s\033[0m\n", rxbuf);
            }
            if (FD_ISSET(0, &readfds)) {
                fgets(txbuf, sizeof(txbuf), stdin);
                znet_send(znet.sock, txbuf, strlen(txbuf) - 1);
            }
        }
    }

    return 0;
}
